package com.ywyt.work;

import com.rabbitmq.client.*;
import com.ywyt.util.ConnUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class WorkConsumer1 {
    @Test
    public void receive() throws IOException, TimeoutException {
        //建立连接
        Connection connection = ConnUtil.getConnection();
        //获取channel
        final Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(WorkProvider.QUEUE_NAME,false,false,false,null);
        //指定每次消费的消息数
        channel.basicQos(1);
        //创建consumer
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String msg = new String(body,"UTF-8");
                System.out.println("一"+msg);
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //消费消息，并调用consumer的回调函数
        channel.basicConsume(WorkProvider.QUEUE_NAME,false,defaultConsumer);
        System.in.read();
        //释放资源
        channel.close();
        connection.close();
    }
}
